package com.zhrj.exam.service.Impl;

import com.zhrj.exam.service.AuthService;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private RestTemplate restTemplate;

    @Override
//    @Async("taskExecutor")
    public String getAuthToken(String tenantId, String username, String password) {
        String url = "http://localhost:80/blade-auth/token";

        // 构造请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");

        // 构造请求体（form-data 格式）
        Map<String, String> params = new HashMap<>();
        params.put("grantType", "password");
        params.put("tenantId", tenantId);
        params.put("username", username);
        params.put("password", password);

        // 构造请求体
        String requestBody = params.entrySet()
                .stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .reduce((p1, p2) -> p1 + "&" + p2)
                .orElse("");

        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, Object> responseBody = response.getBody();
            Map<String, Object> data = (Map<String, Object>) responseBody.get("data"); // 解析 data 字段
            if (data != null && data.get("accessToken") != null) {
                return data.get("accessToken").toString();
            }
        }
        return null;
    }
}
